
import cv2 
import os
from PIL import Image
import dlib
detector = dlib.get_frontal_face_detector()

def eachFile(filepath):
    filepath=os.path.join('%s\%s' % (filepath, "source"))
    pathDir =  os.listdir(filepath)
    for allDir in pathDir:
        child = os.path.join('%s\%s' % (filepath, allDir))
        findface(child)

def findface(file):
    global path
    img=cv2.imread(file)
    simg=cv2.imread(file)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    faces = face_cascade.detectMultiScale(
        gray,
        scaleFactor = 1.30,
        minNeighbors = 3,
        minSize = (250,250),
        flags = cv2.CASCADE_SCALE_IMAGE
    )
    print("发现{0}个人脸!".format(len(faces)))
    print(file)
    for(x,y,w,h) in faces:
        cv2.rectangle(simg,(x,y),(x+w,y+w),(0,255,0),3)
    show(simg)
    #print(faces[0])
    #print(faces[0][0])
    if(len(faces)==0):
        cv2.imwrite(os.path.join(path,"failed",os.path.split(os.path.realpath(file))[1]),img)
    elif (len(faces)==1):
        filename=os.path.join(path,"successful",os.path.split(os.path.realpath(file))[1])
        #filename="d:/python/successful/"+os.path.split(os.path.realpath(file))[1]
        save(img,filename,faces[0][0],faces[0][1],faces[0][2])
    elif (len(faces)>1):
        i=0
        for(x,y,w,h) in faces:
            '''
            p=0.3
            ww=int(w*0.2)
            y1=int(((w+ww*2)/0.6875)*p)
            y2=int(((w+ww*2)/0.6875)*(1-p))
            crop_img = img[y-y1:y+y2,x-ww:x+w+ww] 
            res = cv2.resize(crop_img,(390, 567), interpolation = cv2.INTER_CUBIC)
            filename="d:/python/successful/"+os.path.split(os.path.realpath(file))[1]+str(i)+".jpg"
            cv2.imwrite(filename,res)
            Image.open(filename).save(filename,None,dpi=(300.0,300.0))
            cv2.rectangle(img,(x,y),(x+w,y+w),(0,255,0),3)
            cv2.imshow("image", res)
            '''
            filename=os.path.join(path,"repeat",os.path.split(os.path.realpath(file))[1]+str(i)+".jpg")
            #filename="d:/python/repeat/"+os.path.split(os.path.realpath(file))[1]+str(i)+".jpg"
            
            save(img,filename,x,y,w)
            i+=1
        cv2.imwrite(os.path.join(path,"repeat",os.path.split(os.path.realpath(file))[1]),simg)
     
    
 
    cv2.waitKey (1000)  
    cv2.destroyAllWindows() 

def show(img):
    max=800
    print(img.shape)
    hight=img.shape[0]
    wight=img.shape[1]
    if(hight>wight):
        p=float(wight/hight)
        hight=max
        wight=int(hight*p)
    else:
        p=float(hight/wight)
        wight=max
        hight=int(wight*p)
    res = cv2.resize(img,(wight,hight), interpolation = cv2.INTER_CUBIC)
    cv2.namedWindow("enhanced",0)
    cv2.resizeWindow("enhanced", wight,hight)
    cv2.imshow("enhanced", img) 

def save(img,filepath,x,y,w):
    width= 390 #宽
    hight= 567 #高
    p=0.25 #上下比例
    ww=int(w*0.15) #扩展比例
    y1=int(((w+ww*2)/(width/hight))*p)
    y2=int(((w+ww*2)/(width/hight))*(1-p))
    crop_img = img[y-y1:y+y2,x-ww:x+w+ww] 
    print(crop_img.shape)
        
    try:
        res = cv2.resize(crop_img,(width, hight), interpolation = cv2.INTER_CUBIC)
        cv2.imwrite(filepath,res)
        Image.open(filepath).save(filepath,None,dpi=(300.0,300.0))
        #cv2.rectangle(img,(x,y),(x+w,y+w),(255,0,0),3)
        cv2.imshow("image", res)

    except :
        res = None
        print("error")
        pass

def mkdir(path):
    # 引入模块
    import os
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")
    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path)
        print(path + ' 创建成功')
        return True
    else:
        # 如果目录存在则不创建，并提示目录已存在
        print(path + ' 目录已存在')
        return False

if __name__ =="__main__":
    global path
    path=os.path.split(os.path.realpath(__file__))[0]
    print(path)
    mkdir(path+"/source")
    mkdir(path+"/repeat")
    mkdir(path+"/successful")
    mkdir(path+"/failed")
    #print(os.path.split(os.path.realpath(__file__))[1])

    eachFile(os.path.split(os.path.realpath(__file__))[0])
    #input("enter:")
